<template>
	<view>
		<!-- 收银台 -->
		<view class="edgeInsetTop"></view>
		<NavTitle titleKey="commonTitle.余额详情" />
		<view class="wanl-pay">
			<view class="price-box">
				<text class="text-df">{{order_no}}</text>
				<text class="wanl-pip text-price margin-top-sm">{{price}}</text>
			</view>
			<view class="list-box">
				<view class="item" v-for="(item, index) in payList" :key="index">
					
					<text v-if="item.type !== 'russianBank' && item.type !=='balance'" :class="'wlIcon-'+ item.type +'-pay'"></text>
					<text v-if="item.type === 'russianBank'"><image class="flag-icon" src="/static/images/guoqi/Mongolian.png" mode="aspectFill"/></text>
					<text v-if="item.type === 'balance' && is_ip_cn" :class="'wlIcon-'+ item.type +'-pay'"></text>
					<text v-if="item.type === 'balance' && !is_ip_cn"><image class="flag-icon" src="/static/images/guoqi/mg.png" mode="aspectFill"/></text>
					<view class="action">
						<text class="title wanl-pip">{{item.name}}</text>
						<view v-if="item.type == 'balance'">
							<text v-if="isbalance">{{$t('pages.user.money.可用余额')}} ￥{{user.money}}</text>
							<text v-else>{{$t('pages.user.money.余额不足')}}，{{$t('pages.user.money.可用余额')}} ￥{{user.money}}</text>
						</view>
						<view v-else>{{item.describe}}</view>
					</view>
					<view class="radio text-xxl" v-if="item.state" @tap="onSelect(index)">
						<text v-if="item.select" class="wlIcon-xuanze-danxuan wanl-orange"></text>
						<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
					</view>
					<view class="radio text-xxl" v-else>
						<text class="wlIcon-xuanze-danxuan wanl-gray-light"></text>
					</view>
				</view>
			</view>
			<view v-if="disabled">
				<button class="mix-btn wanl-bg-redorange"> <text class="wlIcon-jiazai wlIconfont-spin margin-right-xs"></text>{{$t('pages.user.money.正在支付中')}} </button>
			</view>
			<view v-else>
				<button v-if="payNum == 1" class="mix-btn wanl-bg-redorange" @tap="confirm()"> {{$t('pages.user.money.正在支付中')}} </button>
				<button v-else class="mix-btn wanl-bg-redorange" @tap="confirm()"> {{$t('pages.user.money.合并支付')}} </button>
			</view>
			<view class="footer text-center">
				<view class="text-sm" v-if="order_pay_no">{{order_type === 'groups' ? $t('pages.user.money.拼团'):''}}{{$t('pages.user.money.交易号')}}：{{order_pay_no}}</view>
			</view>
			
			<!-- 密码输入弹窗 -->
					<view class="password-dialog" v-if="showPasswordDialog">
							<view class="dialog-mask" @tap="hidePasswordDialog"></view>
							<view class="dialog-content">
								<view class="dialog-title">{{$t('pages.user.money.请输入支付密码')}}</view>
								<view class="password-input">
									<input 
										type="password" 
										v-model="password" 
										:focus="showPasswordDialog"
										:placeholder="$t('pages.user.money.请输入任意字符密码')"
										class="form-control"
									/>
								</view>
								<view class="dialog-buttons">
									<button class="dialog-button cancel" @tap="hidePasswordDialog">{{$t('pages.user.money.取消')}}</button>
									<button 
										class="dialog-button confirm" 
										@tap="submitPassword"
									>
										{{$t('pages.user.money.确定')}}
									</button>
								</view>
							</view>
					</view>
		
			
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex';
	export default {
		data() {
			return {
				// 新增密码相关变量
				showPasswordDialog: false,
				password: '',
				currentPayMethod: null, // 记录当前选择的支付方式
				is_ip_cn:true,
				token: '',
				disabled: false,
				price:'0.00',
				isbalance: false,
				order_type: 'goods',
				order_no: '',
				order_pay_no: '',
				payNum: 1, // 支付方式 独立支付-合并支付
				payList: []
			}
		},
		computed: {
			...mapState(['user'])
		},
		watch: {
			price(val, newval) {
				if(val <= parseFloat(this.$store.state.user.money)){
					this.isbalance = true;
					this.getPayment();
				}
			}
		},
		async onLoad(option) {
			await uni.request({
				url: '/wanlshop/user/isIpCn',
				method: 'POST',
				success: res => {
					this.$store.commit('user/setUserInfo', {money: res.data.money});
					this.is_ip_cn = res.data.is_ip_cn;
					// 获取支付列表
					this.getPayment();
				}
			});
			if (option.data) {
				var sum = 0, 
					data = JSON.parse(option.data), 
					order_ids = [];
				if (data.length <= 1) {
					this.price = data[0].price;
					this.order_type = data[0].type;
					this.order_no = `${data[0].type == 'groups' ? '拼团':''}订单号：${data[0].order_no}`;
					this.order_pay_no = data[0].pay_no;
					this.order_id = data[0].order_id;
				}else{
					data.forEach(item => {
						sum = this.$wanlshop.bcadd(sum, item.price);
						order_ids.push(item.order_id);
					});
					this.price = sum;
					this.order_id = order_ids;
					this.payNum = data.length;
					this.order_no = '合并支付 ' + data.length + '个订单';
				}
				this.token = option.token;
			}else if(option.order_id){
				uni.showLoading({
				    title: '结算中...'
				});
				await uni.request({
					url: '/wanlshop/pay/getPay',
					method: 'POST',
					data: {
						order_id: option.order_id,
						order_type: option.order_type
					},
					success: res => {
						uni.hideLoading();
						this.token = res.data.token;
						this.price = res.data.price;
						this.order_type = res.data.order_type;
						this.order_no = `${res.data.order_type == 'groups' ? '拼团':''}订单号：${res.data.order_no}`;
						this.order_pay_no = res.data.pay_no;
						this.order_id = res.data.order_id;
					}
				});
			}else{
				console.log('非法访问');
			}
		},
		methods: {
			
			// 新增密码相关方法
			showPasswordDialogForBalance(payMethod) {
				this.currentPayMethod = payMethod;
				this.password = '';
				this.showPasswordDialog = true;
			},
			
			hidePasswordDialog() {
				this.showPasswordDialog = false;
				this.disabled = false; // 恢复支付按钮
			},
			
			onPasswordInput(e) {
				this.submitPassword();
			},
			
			submitPassword() {
				if (!this.password) {
					uni.showToast({ title: '请输入密码', icon: 'none' });
					return;
				}
				let rest = {};
				rest.method = this.currentPayMethod;
				rest.type = 'balance';
				// 调用支付方法，传入密码
				this.wanlPay(rest);
				this.hidePasswordDialog();
			},
			
			
			getPayment(){
				let method = 'wap';
				// #ifdef APP-PLUS
				method = 'app';
				// #endif
				// #ifdef MP-BAIDU
				method = 'mini';
				// #endif
				// #ifdef MP-WEIXIN
				method = 'miniapp';
				// #endif
				// #ifdef MP-ALIPAY
				method = 'mini';
				// #endif
				// #ifdef MP-QQ
				method = 'mini';
				// #endif
				this.payList = [{
					name: '余额支付',
					describe: '',
					type: 'balance',
					method: 'balance',
					state: this.isbalance ? true: false, // 是否可用
					select: this.isbalance ? true: false // 是否选中
				}];
				// #ifdef H5
				if(!this.is_ip_cn){
					this.payList.push({
						name: 'Банкны картын төлбөр',
						describe: 'Монголын банкны картын төлбөр',
						type: 'russianBank',
						method: 'russianBank',
						state: true,
						select: this.isbalance ? false : true
					});
				}
				if(this.$jssdk.isWechat()){
					this.payList.push({
						name: '公众号支付',
						describe: '推荐使用公众号支付',
						type: 'wechat',
						method: 'mp',
						state: true,
						select: this.isbalance ? false : true
					});
				}else{
					this.payList.push({
						name: '支付宝',
						describe: '',
						type: 'alipay',
						method: method,
						state: true,
						select: false
					}, {
						name: '微信支付',
						describe: '推荐使用微信支付',
						type: 'wechat',
						method: method,
						state: true,
						select: this.isbalance ? false : true
					});
				}
				// #endif
				// #ifndef H5
				uni.getProvider({
				    service: "payment",
				    success: (e) => {
				        e.provider.map((value) => {
							if (value == 'alipay') {
								this.payList.push({name: '支付宝',describe: '',type: value,method: method,state: true,select: false});
							}else if(value == 'wxpay'){
								this.payList.push({name: '微信支付',describe: '推荐使用微信支付',type: 'wechat',method: method,state: true,select: this.isbalance ? false : true});
							}else if(value == 'baidu'){
								this.payList.push({name: '百度收银台',describe: '',type: value,method: method,state: true,select: false});
							}else if(value == 'appleiap'){
								this.payList.push({name: 'Apple支付',describe: '',type: 'apple',method: method,state: true,select: false});
							}
				        })
				    }
				});
				// #endif
			},
			//确认支付
			confirm() {
				let data = null;
				if (this.disabled) {
					return;
				}
				this.payList.map((value,index,array) => {
				　　if(value.select){
						data = value;
					}else{
						return;
					}
				});
				// 判断支付是否存在
				if (!data) {
					uni.showModal({
					    content: "请选择支付方式",
					    showCancel: false
					});
					return;
				}else{
					this.disabled = true;
					// 如果是余额支付，显示密码弹窗
					if (data.method === 'balance') {
						this.showPasswordDialogForBalance(data.method);
					} 
					
					// 获取小程序code
					// #ifdef MP
					uni.login({
					    success: (e) => {
							this.wanlPay(data, e.code);
					    },
					    fail: (e) => {
					        uni.showModal({
					            content: "无法获取微信code,原因为: " + e.errMsg,
					            showCancel: false
					        })
					    }
					})
					// #endif
					// #ifndef MP
					// 如果是公众号获取code
					this.wanlPay(data);
					// #endif
				}
			},
			
			async wanlPay(data, code = null){
				await uni.request({
					url: '/wanlshop/pay/payment',
					method: 'POST',
					data: {
						order_type: this.order_type,
						type: data.type,
						method: data.method,
						code: code,
						order_id: this.order_id,
						token: this.token,
						password:this.password // 新增密码参数
					},
					success: res => {
						// 余额支付/小程序支付
						switch (data.type) {
						    case 'balance':
						        this.$store.commit('user/setUserInfo', {
						        	money: this.$wanlshop.bcsub(this.$store.state.user.money, this.price)
						        });
						        this.paySuccess();
						        break;
						case 'russianBank':
							this.$wanlshop.msg(res.msg);
							if(res.data){
								location.href=res.data;
							}else{
								uni.showModal({
									content: "支付发起失败",
									showCancel: false
								})
							}
						break;
						    case 'wechat':
								// 微信 H5支付
						        if(data.method == 'wap'){
						        	setTimeout(() => {
						        		uni.showModal({
						        		    content: '请确认微信支付是否已完成',
						        			confirmText: '已完成',
						        			cancelText: '重新支付',
						        		    success: response=> {
						        		        if (response.confirm) {
						        		            this.paySuccess();
						        		        } else if (response.cancel) {
						        		            this.confirm();
						        		        }
						        		    }
						        		});
						        	}, 2000);
						        	// 异步查询是否支付成功
						        	window.location.href = res.data;
								// 微信 APP支付
								}else if(data.method == 'app'){
									uni.requestPayment({
									    provider: 'wxpay',
									    orderInfo: res.data,
									    success: (e) => {
									        console.log("success", e);
									        this.paySuccess();
									    },
									    fail: (e) => {
									        uni.showModal({
									            content: "支付失败,原因为: " + e.errMsg,
									            showCancel: false
									        })
									    },
									    complete: () => {
											this.disabled = false;
									    }
									})
								// 微信 小程序支付
						        }else if(data.method == 'miniapp'){
									uni.requestPayment({
									    appId: res.data.appId,
									    nonceStr: res.data.nonceStr,
									    package: res.data.package,
									    paySign: res.data.paySign,
										signType: res.data.signType,
										timeStamp: res.data.timeStamp,
									    success: (e) => {
									        this.paySuccess();
									    },
									    fail: (e) => {
									        uni.showModal({
									            content: "支付失败,原因为: " + e.errMsg,
									            showCancel: false
									        })
									    }
									})
								// 微信 公众平台支付
								}else if(data.method == 'mp'){
									this.$jssdk.wxpay({
										data: res.data,
										success: e => {
											this.paySuccess();
										},
										fail: err => {
											if (err.errMsg == "chooseWXPay:ok") {
												this.$wanlshop.msg('支付成功');
											}else if (err.errMsg == "chooseWXPay:cancel") {
												this.$wanlshop.msg('支付失败，取消支付');
											}else if (err.errMsg == "chooseWXPay:fail") {
												this.$wanlshop.msg('支付失败');
											}
										}
									})
								}
						        break;
						    case 'alipay':
						        if(data.method == 'wap'){
									this.disabled = false;
									if(this.order_type === 'goods'){
										this.$store.commit('statistics/order', {
											pay: this.$wanlshop.bcsub(this.$store.state.statistics.order.pay, this.payNum),
											delive: this.$wanlshop.bcadd(this.$store.state.statistics.order.delive, this.payNum)
										});
									}
									document.write(res.data);
								}else if(data.method == 'app'){
									uni.requestPayment({
									    provider: 'alipay',
									    orderInfo: res.data,
									    success: (e) => {
									        console.log("success", e);
									        this.paySuccess();
									    },
									    fail: (e) => {
									        uni.showModal({
									            content: "支付失败,原因为: " + e.errMsg,
									            showCancel: false
									        })
									    },
									    complete: () => {
											this.disabled = false;
									    }
									})
								}
								break;
						} 
					}
				});
			},
			onSelect(key){
				this.payList.map((value,index,array) => {
				　　if(index == key){
						value.select = !value.select;
					}else{
						value.select = false;
					}
				});
			},
			// 支付成功
			paySuccess(){
				this.disabled = false;
				if(this.order_type === 'goods'){
					this.$store.commit('statistics/order', {
						pay: this.$wanlshop.bcsub(this.$store.state.statistics.order.pay, this.payNum),
						delive: this.$wanlshop.bcadd(this.$store.state.statistics.order.delive, this.payNum)
					});
				}
				this.$wanlshop.to(`/pages/page/success?type=pay&order_type=${this.order_type ? this.order_type:'goods'}`);
			}
		}
	}
</script>

<style>
	
	.flag-icon {
	  width: 54rpx;
	  height: 54rpx;
	  display: block;
	  margin: 0 auto 8rpx;
	  object-fit: contain;
	}
	
	/* 新增密码弹窗样式 */
		.password-dialog {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 9999;
		}
		
		.dialog-mask {
			position: absolute;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
		}
		
		.dialog-content {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 80%;
			background-color: #fff;
			border-radius: 10rpx;
			padding: 30rpx;
			box-sizing: border-box;
		}
		
		.dialog-title {
			font-size: 32rpx;
			text-align: center;
			margin-bottom: 40rpx;
			font-weight: bold;
		}
		
		.password-input {
			position: relative;
			margin-bottom: 40rpx;
		}
		
		.hidden-input {
			position: absolute;
			width: 100%;
			height: 100%;
			opacity: 0;
			z-index: -1;
		}
		
		.password-display {
			display: flex;
			justify-content: space-between;
		}
		
		.password-item {
			width: 80rpx;
			height: 80rpx;
			border: 2rpx solid #ddd;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
		}
		
		.cursor {
			animation: blink 1s infinite;
			color: #007aff;
		}
		
		@keyframes blink {
			0% { opacity: 1; }
			50% { opacity: 0; }
			100% { opacity: 1; }
		}
		
		.dialog-buttons {
			display: flex;
			justify-content: space-between;
		}
		
		.dialog-button {
			flex: 1;
			margin: 0 10rpx;
			border-radius: 50rpx;
		}
		
		.cancel {
			background-color: #f8f8f8;
			color: #333;
		}
		
		.confirm {
			background-color: #007aff;
			color: #fff;
		}
		
		.confirm[disabled] {
			background-color: #ccc;
		}
	
	page{
		background-color: white;
	}
	radio-group {
	    display: block;
	}
</style>
